<template>
	<div class="login-page">
		<a-card>
			<a-form layout="vertical" :model="form" :rules="rules" ref="loginForm">
				<!-- 角色选择 -->
				<a-form-item label="选择角色" required>
					<a-radio-group v-model:value="role" @change="clearForm">
						<a-radio value="user">用户</a-radio>
						<a-radio value="landlord">房东</a-radio>
						<a-radio value="admin">管理员</a-radio>
					</a-radio-group>
				</a-form-item>

				<!-- 邮箱 -->
				<a-form-item label="邮箱" name="email">
					<a-input v-model:value="form.email" placeholder="请输入邮箱" />
				</a-form-item>

				<!-- 密码 -->
				<a-form-item label="密码" name="password">
					<a-input-password v-model:value="form.password" placeholder="请输入密码" />
				</a-form-item>

				<!-- 验证码 -->
				<a-form-item label="验证码" name="code">
					<div class="captcha-container">
						<a-input v-model:value="form.code" placeholder="请输入验证码" class="captcha-input" />
						<img :src="captchaImage" alt="验证码" @click="refreshCaptcha" class="captcha-image" />
					</div>
				</a-form-item>

				<!-- 登录按钮 -->
				<a-form-item>
					<a-button type="primary" block @click="login">登录</a-button>
				</a-form-item>

				<div class="tip">
					<text> 没有账号？点击<a @click="goToRegister">注册</a> </text>
					<text> 密码忘记了？点击<a @click="goToForget">重置密码</a> </text>
				</div>
			</a-form>
		</a-card>
	</div>
</template>

<script>
import authApi from '@/api/authApi'
import { message } from 'ant-design-vue'
import router from '@/router'
import eventBus from '@/utils/eventBus'

export default {
	data() {
		return {
			role: 'user', // 默认角色
			form: {
				email: '',
				password: '',
				code: ''
			},
			captchaImage: '/api/user/auth/login/code',
			rules: {
				email: [
					{ required: true, message: '邮箱不能为空', trigger: 'blur' },
					{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
				],
				password: [
					{ required: true, message: '密码不能为空', trigger: 'blur' },
					{ min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
				],
				code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
			}
		}
	},
	methods: {
		refreshCaptcha() {
			this.captchaImage = `/api/${this.role}/auth/login/code?timestamp=${Date.now()}`
		},
		clearForm() {
			this.form.email = ''
			this.form.password = ''
			this.form.code = ''
			this.refreshCaptcha()
		},
		login() {
			this.$refs.loginForm.validate().then(() => {
				const loginApi =
					this.role === 'user'
						? authApi.userLogin
						: this.role === 'landlord'
							? authApi.landlordLogin
							: authApi.adminLogin

				loginApi({
					email: this.form.email.trim(),
					password: this.form.password.trim(),
					code: this.form.code.trim()
				})
					.then((res) => {
						localStorage.setItem('satoken', res.data.satoken);
						localStorage.setItem('name', res.data.name);
						localStorage.setItem('id', res.data.id);
						localStorage.setItem('role', this.role);

						message.success('登录成功')
						// 通知 Navbar 更新用户状态
						eventBus.emit('userLoggedIn')
						if (this.role === 'admin'){
							router.push('/admin-center')
						}else {
							// //登陆成功之后回到上一页
							// router.go(-1);
							// 登录成功后跳转回上一个页面
							const fromPath = sessionStorage.getItem('fromPath');
							if (fromPath) {
								this.$router.push(fromPath); // 跳转回上一个页面
								sessionStorage.removeItem('fromPath'); // 清除存储的路由
							} else {
								this.$router.push('/'); // 如果没有记录，则跳转到首页
							}
						}
					})
					.catch((err) => {
						console.error(err.response.data.message)
						this.refreshCaptcha()
					})
			})
		},
		goToRegister() {
			router.push('/register')
		},
		goToForget() {
			router.push('/forget-pass')
		}
	},
	mounted() {
		this.refreshCaptcha()
	}
}
</script>

<style scoped>
.login-page {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 90vh;
	background: #f0f2f5;
}

.captcha-container {
	display: flex;
	align-items: center;
}

.captcha-image {
	margin-left: 1rem;
	cursor: pointer;
}

.captcha-input {
	cursor: pointer;
	width: 70%;
}

.tip {
	display: flex;
	flex-direction: column;
	gap: 1rem;
	align-items: center;
}
</style>
